package com.example.batterynotification;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.os.SystemClock;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class batteryLevelReceiver extends BroadcastReceiver {
	private static int previousLevel = 0;
	private Preferences pref;
	private AppContext appContext;
	private long startTime;
	private int highNotificationLevel;
	private int currentLevel;
	private static int counter = 0;
	private static float totalTime = 0;

	enum Elevel {
		HIGHLEVEL, LOWLEVEL
	};

	@Override
	public void onReceive(final Context context, final Intent intent) {
		// check if the battery level reached the requires level or not
		appContext = new AppContext(context);

		pref = new Preferences(appContext);
		currentLevel = intent.getIntExtra("level", 0);

		Log.i("TI", "current level =" + currentLevel);

		if (currentLevel != previousLevel) {
			// updateWidgetLevelImage(currentLevel,context);the widget will be
			// removed
			new ManageNotifications(appContext);

			Log.i("TI", "current level = " + Integer.toString(currentLevel)
					+ "previous level = " + Integer.toString(previousLevel));
			if (Preferences.getBoolPreferences("HighSwitch")) {
				highNotificationLevel = Preferences
						.getIntPreferences("prefHighBatteryLevel");
				Log.i("TI", "high " + highNotificationLevel);
				Log.i("TI", "current " + currentLevel);
				if (highNotificationLevel == currentLevel) {
					Toast.makeText(context, "battery full", Toast.LENGTH_SHORT)
							.show();
					ManageNotifications.updateMainNotification("" + currentLevel,
						"", "");			
					BatteryReceiverForeground.toggleRemainingTimeView();					
					executeServices(context, Elevel.HIGHLEVEL);
				}
				if (intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0) == BatteryManager.BATTERY_STATUS_CHARGING
						&& (highNotificationLevel > currentLevel)) {
					
					Log.i("TI", "Entered if BATTERY_STATUS_CHARGING");
					if (!BatteryReceiverForegroundResources
							.isACChargingTimerStarted()) {
						startTime = SystemClock.uptimeMillis();
						BatteryReceiverForegroundResources
								.setACChargingTimerStarted(true);
						if(Preferences.getBoolPreferences("isMainActivityActive"))
						{
								BatteryReceiverForeground.ShowACChargingTime();
								BatteryReceiverForeground.toggleRemainingTimeView();
						}						
						Log.i("TI", "Timer Not Started");
						Log.i("TI", "Timer Update=" +Integer.parseInt(Preferences.getStringPreferences("ChargingTimer")) );						
						Preferences.savePreferences("startLevel", currentLevel);
					} else {
						Log.i("TI", "Timer Started");
//						int remainingTime=
								RemainingTime(true);
							if(Preferences.getBoolPreferences("isMainActivityActive"))
							{
									BatteryReceiverForeground.ShowACChargingTime();
									BatteryReceiverForeground.toggleRemainingTimeView();				
							}
								Log.i("TI", "After RemainingTime" +Integer.parseInt(Preferences.getStringPreferences("ChargingTimer")) );													
						        ManageNotifications.updateMainNotification("" + currentLevel,
								Util.MilliSecondsConvert(Integer.parseInt(Preferences.getStringPreferences("ChargingTimer"))*(highNotificationLevel-currentLevel)), "Time to reach "+Integer.toString(highNotificationLevel)+"%");						
					}
				}
			}
			if (Preferences.getBoolPreferences("LowSwitch")) {
				int lowNotificationLevel = Preferences
						.getIntPreferences("prefLowBatteryLevel");
				if (!BatteryReceiverForegroundResources
						.isDischargingTimerStarted()) {
					startTime = SystemClock.uptimeMillis();
					BatteryReceiverForegroundResources
							.setDischargingTimerStarted(true);
					if(Preferences.getBoolPreferences("isMainActivityActive"))
					{
							BatteryReceiverForeground.ShowDischargingTime();
							BatteryReceiverForeground.toggleRemainingTimeView();							
					}						
					Log.i("TI", "Discharing Timer Not started");
					Preferences.savePreferences("startDischargeLevel",
							currentLevel);
				} else {
					Log.i("TI", "Discharing Timer Started");
					int remainingTime=RemainingTime(false);
					if(Preferences.getBoolPreferences("isMainActivityActive"))
					{
							BatteryReceiverForeground.ShowDischargingTime();
							BatteryReceiverForeground.toggleRemainingTimeView();							
					}					
					ManageNotifications.updateMainNotification("" + currentLevel,
							Util.MilliSecondsConvert(Integer.parseInt(Preferences.getStringPreferences("DischargingTimer"))*(currentLevel-lowNotificationLevel)),Integer.toString(lowNotificationLevel));					
				}
				Log.i("LC", "" + lowNotificationLevel);
				if (lowNotificationLevel == currentLevel) {
					Toast.makeText(context, "battery low", Toast.LENGTH_SHORT)
							.show();
					BatteryReceiverForeground.toggleRemainingTimeView();					
					executeServices(context, Elevel.LOWLEVEL);
				}
			}

			previousLevel = currentLevel;
		}
	}

	private void executeServices(final Context context, Elevel elevel) {
		Log.i("LC", "executeServices()");
		if (elevel == Elevel.HIGHLEVEL) {
			ManageNotifications.batteryFullNotification();
		} else if (elevel == Elevel.LOWLEVEL) {
			ManageNotifications.batteryLowNotification();
		}

		// if(Preferences.getBoolPreferences(muteLabel)==false)
		// {
		// Intent mIntent= new Intent(context, AudioService.class);
		// context.startService(mIntent);
		// }
		// if(Preferences.getBoolPreferences(VibrationLabel)==true)
		// {
		// Intent vibratorIntent=new Intent(context,VibrationService.class);
		// context.startService(vibratorIntent);
		// }

	}

	private void updateWidgetLevelImage(int level, Context context) {
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
				R.layout.widget_layout);
		remoteViews.setTextViewText(R.id.Text1, level + "%");

		if (level <= 5 && level > 0)
			remoteViews.setImageViewResource(R.id.widgetImage,
					R.drawable.state5);
		else if (level < 3)
			remoteViews.setImageViewResource(R.id.widgetImage,
					R.drawable.stateempty);
		else if (level >= 5 && level < 10)
			remoteViews.setImageViewResource(R.id.widgetImage,
					R.drawable.state10);
		else if (level >= 10 && level < 20)
			remoteViews.setImageViewResource(R.id.widgetImage,
					R.drawable.state20);
		else if (level >= 20 && level < 30)
			remoteViews.setImageViewResource(R.id.widgetImage,
					R.drawable.state30);
		else if ((level >= 30) && level < 40)
			remoteViews.setImageViewResource(R.id.widgetImage,
					R.drawable.state40);
		else if ((level >= 40) && level < 50)
			remoteViews.setImageViewResource(R.id.widgetImage,
					R.drawable.state50);
		else if ((level >= 50) && level < 60)
			remoteViews.setImageViewResource(R.id.widgetImage,
					R.drawable.state60);
		else if ((level >= 60) && level < 70)
			remoteViews.setImageViewResource(R.id.widgetImage,
					R.drawable.state70);
		else if ((level >= 70) && level < 80)
			remoteViews.setImageViewResource(R.id.widgetImage,
					R.drawable.state80);
		else if ((level >= 80) && level < 90)
			remoteViews.setImageViewResource(R.id.widgetImage,
					R.drawable.state90);
		else if ((level >= 90) && level <= 100)
			remoteViews.setImageViewResource(R.id.widgetImage,
					R.drawable.statefull);

		pushWidgetUpdate(context, remoteViews);
	}

	public static void pushWidgetUpdate(Context context, RemoteViews remoteViews) {
		ComponentName myWidget = new ComponentName(context,
				AppWidgetProvider.class);
		AppWidgetManager manager = AppWidgetManager.getInstance(context);
		manager.updateAppWidget(myWidget, remoteViews);
	}

	int RemainingTime(Boolean isCharging) {
		long timeInterval = SystemClock.uptimeMillis() - startTime;
		float seconds =  timeInterval / 1000;
		float minutes = seconds / 60;
		Log.i("TI", "time between 2 levels = " + Float.toString(minutes)
				+ "minutes");
		Log.i("TI", "time between 2 levels = " + Float.toString(seconds)
				+ " seconds");

		startTime = SystemClock.uptimeMillis();
		Log.i("TI",
				"start level =" + Preferences.getIntPreferences("startLevel"));
		int temp = Preferences.getIntPreferences("startLevel");
		if (currentLevel > temp && isCharging) {
			counter++;
			totalTime += timeInterval;
			Log.i("TI", "counter = " + Integer.toString(counter)
					+ "total time = " + Float.toString(totalTime));

			Log.i("TI", "Current Level =" + currentLevel + "& Start Level = "
					+ Preferences.getIntPreferences("startLevel"));

			Preferences.savePreferences("ChargingTimer",
					Integer.toString((int) (totalTime / counter)));
			return (int)(totalTime/counter);
		} 
		else if (currentLevel < temp && !isCharging) {
			counter++;
			totalTime += seconds;
			Log.i("TI", "counter = " + Integer.toString(counter)
					+ "total time = " + Float.toString(totalTime));

			Log.i("TI", "Current Level =" + currentLevel + "& Start Level = "
					+ Preferences.getIntPreferences("startLevel"));
			Preferences.savePreferences("DischargingTimer",
					Integer.toString((int) (totalTime / counter)));
			return (int)(totalTime/counter);		
		}
			return 0;
	}

	static public void setCounter(int inCounter) {
		counter = inCounter;
	}

	static public void setTotalTime(float itotalTime) {
		totalTime = itotalTime;
	}
}